package com.mz.mattress.client.timer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

//    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();

    // 用来存在线连接数
    private static final Map<String, Session> sessionPool = new HashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
//            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("websocket_new_connect,userId={},connect_total={}", userId, sessionPool.size());
        } catch (Exception e) {
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("websocket_get_message=" + message);
    }

    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        log.info("sessionPool_size=" + sessionPool.size());

        if (session == null) {
            log.info("websocket_null_userId=" + userId);
            return;
        }

        if (!session.isOpen()) {
            sessionPool.remove(userId);
            log.info("websocket_remove_userId=" + userId);
        }

        try {
            session.getAsyncRemote().sendText(message);
            log.info("websocket_send_userId={},message={}", userId, message);
        } catch (Throwable e) {
            //忽略异常
        }
    }

}
